package com.qfhd.soft.cjzcore.Core;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.qfhd.soft.cjzcore.CJZConstant;
import com.qfhd.soft.cjzcore.TaskCenter.CJAdCenter;
import com.qfhd.soft.cjzcore.UI.Listener.CJListener;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;

public class CJFile {
    private Context mContext;
    private String m_dataFolder;

    private static CJFile cjFile;

    public static CJFile getInstance() {
        if (cjFile == null) {
            synchronized (CJFile.class) {
                cjFile = new CJFile();
            }
        }
        return cjFile;
    }

    public void init(Context context) {
        mContext = context;
    }

    public String getDataFolder() {
        if (TextUtils.isEmpty(m_dataFolder)) {
            String sd = getDiscFolder(mContext);
            if (!TextUtils.isEmpty(sd)) {
                m_dataFolder = sd + CJZConstant.File.dataFolder;
                File destDir = new File(m_dataFolder);
                if (!destDir.exists()) {
                    boolean ret = destDir.mkdirs();
                    if(ret){
                        CJLogger.v("create dataFolder success path:"+m_dataFolder);
                    }
                    else{
                        CJLogger.v("create dataFolder failed");
                    }
                }
            }
        }
        CJLogger.v("getDataFolder:"+m_dataFolder);
        return m_dataFolder;
    }

    public static String getDiscFolder(Context context) {
        File dir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            dir = Environment.getExternalStorageDirectory();
            if (!dir.exists()) {
                dir = context.getExternalCacheDir();
            }
        } else {
            dir = Environment.getDownloadCacheDirectory();
        }
        return dir.toString();
    }

    public static boolean saveDeviceInfoToFile(Context context, String deviceInfo) {
        try {
            File file = new File(CJFile.getInstance().getDataFolder() + "/" + CJZConstant.File.deviceFile);
            CJLogger.v("saveDeviceInfoToFile path:" + file.getPath());
            if (!file.exists()) file.createNewFile();

            FileOutputStream fos = new FileOutputStream(file);
            String data = deviceInfo;
            fos.write(data.getBytes());

            fos.flush();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            CJLogger.v("saveDeviceInfoToFile e:" + e.toString());
        }
        return false;
    }

    public static String getDeviceInfoFromFile(Context context) {
        String res = null;
        try {
            File file = new File(CJFile.getInstance().getDataFolder() + "/" + CJZConstant.File.deviceFile);
            CJLogger.v("file path:" + file.getPath());
            if (!file.exists()) return null;

            FileInputStream fis = new FileInputStream(file);
            int length = fis.available();
            byte[] buffer = new byte[length];
            fis.read(buffer);

            res = new String(buffer, "UTF-8");
            fis.close();
        } catch (Exception e) {
            CJLogger.v("getDeviceInfoFromFile e:" + e.toString());
        }
        return res;
    }

    public static String getFileSieze(long size) {
        DecimalFormat df = new DecimalFormat("0.00");
        long apkSize = size;
        float Msize = 1.0f * 1024 * 1024;
        float Gsize = 1 * 1024 * Msize;
        if ((apkSize / Msize) >= 1024) {
//            return apkSize/Gsize + "." + df.format(apkSize%Gsize) + "GB";
            return df.format(apkSize / Gsize) + "GB";
        } else {
//            return apkSize/Msize + "." + df.format(apkSize%Msize) + "MB";
            return df.format(apkSize / Msize) + "MB";
        }
    }

    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static String getPathByUri(final Activity activity, final Uri uri) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            return path;
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return path;
        } else {
            CJLogger.v("Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

    /**
     * 删除文件，可以是文件或文件夹
     *
     * @param delFile 要删除的文件夹或文件名
     * @return 删除成功返回true，否则返回false
     */
    public static boolean delete(String delFile) {
        File file = new File(delFile);
        if (!file.exists()) {
//            Toast.makeText(HnUiUtils.getContext(), "删除文件失败:" + delFile + "不存在！", Toast.LENGTH_SHORT).show();
            CJLogger.v("删除文件失败:" + delFile + "不存在！");
            return false;
        } else {
            if (file.isFile())
                return deleteSingleFile(delFile);
            else
                return deleteDirectory(delFile);
        }
    }

    /**
     * 删除单个文件
     *
     * @param filePath$Name 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                CJLogger.v("Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return true;
            } else {
                CJLogger.v("删除单个文件" + filePath$Name + "失败！");
                return false;
            }
        } else {
            CJLogger.v("删除单个文件失败：" + filePath$Name + "不存在！");
            return false;
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param filePath 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator))
            filePath = filePath + File.separator;
        File dirFile = new File(filePath);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            CJLogger.v("删除目录失败：" + filePath + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (File file : files) {
            // 删除子文件
            if (file.isFile()) {
                flag = deleteSingleFile(file.getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (file.isDirectory()) {
                flag = deleteDirectory(file
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            CJLogger.v("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            CJLogger.v("Copy_Delete.deleteDirectory: 删除目录" + filePath + "成功！");
            return true;
        } else {
            CJLogger.v("删除目录：" + filePath + "失败！");
            return false;
        }
    }

    /**
     * 获取文件夹大小(递归)
     *
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(File file) {

        long size = 0;
        try {
            java.io.File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);

                } else {
                    size = size + fileList[i].length();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }
}
